import time

from django.core.exceptions import FieldError
from django.core.paginator import Paginator, EmptyPage


# 过滤请求参数
def allow_edit(allow, request):
	data = dict(request.data.items())
	# 去掉不允许修改的字段
	for key in list(data.keys()):
		if key not in allow:
			data.pop(key)
	return data


# 设置任务ID
def set_task_id(case):
	# task_id = f'{case.api.project.mark}::api_ID_{case.api.id}::case_ID_{case.id}::{round(time.time() * 1000)}'
	task_id = f'{case.api.project.mark}::api_ID_{case.api.id}::case_ID_{case.id}'
	return task_id


# 返回分页数据
def get_page(request, db_object, serializer) -> dict:
	"""
	:param request: 请求对象
	:param db_object: model对象
	:param serializer: 序列化对象
	"""
	page_size = request.query_params.get('pageSize')
	page_num = request.query_params.get('pageNum')
	try:
		page_size = 20 if not isinstance(int(page_size), int) else int(page_size)
	except Exception:
		page_size = 20
	try:
		page_num = 1 if not isinstance(int(page_num), int) else int(page_num)
	except Exception:
		page_num = 1

	try:
		db_object_list = Paginator(db_object.objects.filter(deleted=False).order_by('-id'), page_size)
	except FieldError:
		db_object_list = Paginator(db_object.objects.all().order_by('-id'), page_size)
	try:
		page = db_object_list.page(page_num)
	except EmptyPage:
		page = db_object_list.page(1)
	serializer = serializer(page, many=True)
	data = {
		'count': db_object_list.count,
		'list': serializer.data
	}
	return data
